package cn.zwx.canal.tools.hanlder;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.zwx.canal.tools.common.bo.CovertMessageBO;
import cn.zwx.canal.tools.enums.BuisType;
import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;

/**
 * @description: 转换参数
 * @projectName:learn
 * @see:cn.zwx.canal.tools.hanlder
 * @author:zhangwenxue
 * @createTime:2021/1/13 10:26
 * @version:1.0
 */
@Component
public class CovertMessageHandler {

    private Logger logger = LoggerFactory.getLogger(CovertMessageHandler.class);

    private static final String OLD_STR = "old";

    /**
     * 转换发送消息类
     * @param bo 参数转换BO
     * @return
     */
    public Map<String,Object> covertMessageDTO(CovertMessageBO bo) {
        Map<String, Object> returnMap = new LinkedHashMap<>(16);
        // 数据库名称
        returnMap.put("database",bo.getDatabase());
        // 表名称
        returnMap.put("tableName",bo.getTableName());
        // 业务类型 1-新增 2-修改 3-删除
        returnMap.put("busiType",bo.getBusiType());
        // 业务类型描述
        returnMap.put("busiTypeDesc",BuisType.ofValue(bo.getBusiType()));
        // 处理变更之前的数据
        Map<String, String> beforeColumnMap = CollectionUtil.newHashMap();
        if (bo.getBusiType().equals(BuisType.UPDATE.getCode()) ||bo.getBusiType().equals(BuisType.DELETE.getCode())){
            List<CanalEntry.Column> beforeColumnsList = bo.getBeforeColumnsList();
            if (CollectionUtil.isNotEmpty(beforeColumnsList)){
                for (CanalEntry.Column column : beforeColumnsList) {
                    String columnName = column.getName();
                    String columnValue = column.getValue();
                    beforeColumnMap.put(this.underline2Camel(columnName), columnValue);
                }
            }
        }
        // 处理变更之后的数据
        Map<String, String> afterColumnMap = CollectionUtil.newHashMap();
        List<CanalEntry.Column> afterColumnsList = bo.getAfterColumnsList();
        if (CollectionUtil.isNotEmpty(afterColumnsList)){
            for (CanalEntry.Column column : afterColumnsList) {
                String columnName = column.getName();
                String columnValue = column.getValue();
                afterColumnMap.put(this.underline2Camel(columnName), columnValue);
            }
        }else {
            logger.info("业务类型:{},无变更之后的数据",BuisType.ofValue(bo.getBusiType()));
        }

        Map<String, String> changeMap = CollectionUtil.newHashMap();
        // 组装数据
        if (bo.getBusiType().equals(BuisType.INSERT.getCode())||bo.getBusiType().equals(BuisType.UPDATE.getCode())){
            changeMap = afterColumnMap;
        }else {
            changeMap = beforeColumnMap;
        }
            
        for (Map.Entry<String, String> entry : changeMap.entrySet()) {
            if (CollectionUtil.isNotEmpty(afterColumnMap)){
                returnMap.put(entry.getKey(),entry.getValue());
            }
            if (CollectionUtil.isNotEmpty(beforeColumnMap)){
                returnMap.put(OLD_STR+this.captureName(entry.getKey()),beforeColumnMap.get(entry.getKey()));
            }
        }

        logger.info("转换发送消息类转换结果:{}", JSON.toJSONString(returnMap));
        return returnMap;

    }

    /**
     * 将字符串的首字母转大写
     * @param str 需要转换的字符串
     * @return
     */
    private  String captureName(String str) {
        // 进行字母的ascii编码前移，效率要高于截取字符串进行转换的操作
        char[] cs=str.toCharArray();
        cs[0]-=32;
        return String.valueOf(cs);
    }

    /**
     * 下划线转换为驼峰
     *
     * @param line 下划线字符串
     * @param firstIsUpperCase 首字母是否转换为大写
     * @return
     */
    public String underline2Camel(String line, boolean... firstIsUpperCase) {
        String str = "";
        if(StrUtil.isBlank(line)){
            return str;
        } else {
            StringBuilder sb = new StringBuilder();
            String [] strArr;
            // 不包含下划线，且第二个参数是空的
            if(!line.contains("_") && firstIsUpperCase.length == 0){
                sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1));
                str = sb.toString();
            } else if (!line.contains("_") && firstIsUpperCase.length != 0){
                if (!firstIsUpperCase[0]) {
                    sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1));
                    str = sb.toString();
                } else {
                    sb.append(line.substring(0, 1).toUpperCase()).append(line.substring(1));
                    str = sb.toString();
                }
            } else if (line.contains("_") && firstIsUpperCase.length == 0) {
                strArr = line.split("_");
                for (String s : strArr) {
                    sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
                }
                str = sb.toString();
                str = str.substring(0, 1).toLowerCase() + str.substring(1);
            } else if (line.contains("_") && firstIsUpperCase.length != 0) {
                strArr = line.split("_");
                for (String s : strArr) {
                    sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
                }
                if (!firstIsUpperCase[0]) {
                    str = sb.toString();
                    str = str.substring(0, 1).toLowerCase() + str.substring(1);
                } else {
                    str = sb.toString();
                }
            }
        }
        return str;
    }



}
